<?php

/**
 * Created by PhpStorm.
 * User: jingx
 * Date: 2017/6/16
 * Time: 14:01
 */
class WeChatAction extends CommonAction
{
    /**
     * @var WeChatApp
     */
    public $wechat;

    function _initialize()
    {
        require_once(dirname(__DIR__) . '/ORG/wechat/Wx.class.php');
        require_once(dirname(__DIR__) . '/ORG/WeChatApp.class.php');
        $this->wechat = WeChatApp::instance();
    }

    /**
     * 微信公众号接口
     */
    public function response()
    {
        $this->wechat->response();
    }

    /**
     * 网页授权回调地址
     */
    public function oauth2()
    {
        $activity_id = $_SESSION['activity_id'];
        $Activity = D('Activity')->find($activity_id);
        $configs = [
            'appid' => $Activity['app_id'],
            'appsecret' => $Activity['app_secret'],
        ];
        $wechat = new WeChatApp($configs);
        $response = $wechat->getOauthAccessToken();
        $_SESSION['wechat_user'] = $this->wechat->getOauthUserinfo($response['access_token'], $response['openid']);

        $url = $_SESSION['redirect_uri'];
        header('Location: http://' . $url);
    }

    /**
     * 参加活动，这个是推广海报的二维码的地址
     */
    public function signup()
    {
        $activity_id = $_GET['activity_id'];
        $open_id = $_GET['open_id'];
        $_SESSION['activity_id'] = $activity_id;
        $_SESSION['open_id'] = $open_id;
		if(!D('Activity')->where('start_date<='.time().' and end_date>='.time().' and id='.$activity_id)->find()){
			echo '<img src="http://www.zaijiahome.com/res/public/upload/acover.jpg" width="100%" height="100%">';
			exit;
		}
        if (!$_SESSION['wechat_user']) {
            $_SESSION['redirect_uri'] = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $Activity = D('Activity')->find($activity_id);
			
            $configs = [
                'appid' => $Activity['app_id'],
                'appsecret' => $Activity['app_secret'],
            ];
			$wechat = new WeChatApp($configs);
            $url = $wechat->getOauthRedirect('http://www.zaijiahome.com/trends/index.php?m=WeChat&a=oauth2');
			
            header('Location:' . $url);
            return null;
        }
		
        /** @var UserActivityModel $model */
        $model = D('UserActivity');
        $model->joinActivityFrom($activity_id, $_SESSION['wechat_user'], $open_id);
		
        header('Location: ' . $model->activity->guide);
    }

    public function menu()
    {
        $res = $this->wechat->deleteMenu();
        $menu = [
            'button' => [
				[                
					'type' => 'click',
					'name' => '生成海报',
					'key' => '91',
                ],
				[                 
					'type' => 'view',
					'name' => '个人中心',
					'url' => 'http://www.zaijiahome.com/ac/acindex.html?aid=91&appname=gh_ad8a4e1d21d9&actype=6',                    
                ],
            ],
        ];
        $res = $this->wechat->createMenu($menu);
        var_dump($res);
    }

    public function uploadImg()
    {
        try {
            if ($_FILES["AidImg"]["size"] != 0) {
                $upload = new UploadFile();// 实例化上传类
                $upload->maxSize = 3145728;// 设置附件上传大小
                $upload->allowExts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
                $upload->saveRule = 'uniqid';

                $subPath = 'public/upload/images/' . date('Ym') . '/' . date('d') . '/';
                $imageRoot = RES_ROOT . $subPath;
                mkdir($imageRoot, 0777, true);

                $upload->savePath = $imageRoot; // 设置附件上传（子）目录
                // 上传文件
                $upload->upload();
                $info = $upload->getUploadFileInfo();
                $imgUrl = PIC_ROOT . $subPath . $info[0]['savename'];
            }
        } catch (Exception $e) {
            echo "<script>parent.callback('图片上传失败',false)</script>";
            return;
        }
        echo "<script>parent.callback('$imgUrl',true)</script>";
    }


}